package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.controller.debug.ServletDebugInfo;
import com.conversationboard.logger.Logger;
import com.conversationboard.model.BoardAdminList;
import com.conversationboard.model.BoardAdmins;
import com.conversationboard.model.Role;
import com.conversationboard.model.User;
import com.conversationboard.security.EncryptedKey;
import com.conversationboard.security.EncryptionException;

@WebServlet(name = "AdminRevokePrivilegesControllerServlet", urlPatterns = "/Admin/AdminRevokePrivilegesControllerServlet")
public class AdminRevokePrivilegesControllerServlet extends HttpServlet {

	private static final long serialVersionUID = 4958362243486699653L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		try {

			User user = User.get(request.getUserPrincipal().getName());

			if (user.getRole() != Role.SiteAdmin) {
				return;
			}

			/* Check authorisation */

			String key = request.getParameter("key");
			EncryptedKey encryptedKey = new EncryptedKey();

			if (!encryptedKey.isValid(key, user.getLoginId())) {
				Logger.log(new Date(), "Part 1 of error: " + this.getClass().getName(), user);
				String postRequest = ServletDebugInfo.getRawRequest(request);
				Logger.log(new Date(), "Part 2 of error:\n\n" + postRequest, user);
				return;
			}

			String selected = request.getParameter("radio");

			int id = Integer.parseInt(selected);

			String loginId = request.getParameter("loginid" + id);
			int boardId = Integer.parseInt(request.getParameter("boardid" + id));

			User boardAdmin = User.get(loginId);

			BoardAdminList boardAdminList = boardAdmin.getBoardAdminList();

			boardAdminList.getBoardAdminList().remove(boardId);

			if (boardAdminList.getBoardAdminList().size() != 0) {
				boardAdminList.persist(loginId);
			} else {
				BoardAdmins.revokeAll(loginId);
			}

			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
			request.setAttribute("message", "Privileges successfully revoked.");

			dispatcher.forward(request, response);

		} catch (EncryptionException e) {
			throw new ServletException(e);
		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}

}
